package com.atues.kuangshengjuc.add;

public class SemaphoreDemo {
    //可以类似与3个停车位，有六辆车来停车，
    //用于多线程控制线程量
    public static void main(String[] args) {
        //创建一个Semaphore对象，初始许可数为3
        java.util.concurrent.Semaphore semaphore = new java.util.concurrent.Semaphore(3);

        //创建5个线程，每个线程尝试获取一个许可
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    //获取许可
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "获得许可");
                    //模拟执行任务
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //释放许可
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + "释放许可");
                }
            }, "线程" + i).start();
        }
    }
}
